<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTag } from 'element-plus'
import { Table } from '@/components/Table'
import { getTableListApi, saveTableApi, delTableListApi,getRoleApi } from '@/api/user'
import { getUserPageApi } from '@/api/account'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { he } from 'element-plus/es/locale'

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getTableListApi({
      page: unref(currentPage),
      pagesize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.items,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    setTimeout(() => {
      saveLoading.value = false
      dialogVisible.value = false
    }, 1000)
    getList()
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('admin.id'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          return (
            <div 
              style="
                color: #409eff; 
                cursor: pointer; 
                width: 100%;
                height: 100%;
                padding: 8px;
                margin: -8px;
                align-items: center;
                transition: background-color 0.2s;
              "
              onMouseenter={(e: MouseEvent) => {
                const target = e.target as HTMLElement
                if (target) {
                  target.style.backgroundColor = '#f5f7fa'
                }
              }}
              onMouseleave={(e: MouseEvent) => {
                const target = e.target as HTMLElement
                if (target) {
                  target.style.backgroundColor = 'transparent'
                }
              }}
              onClick={() => action(data.row, 'edit')}
            >
              {data.row.id}
            </div>
          )
        }
      }
    }
  },
  {
    field: 'account',
    label: t('admin.account'),
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'roleid',
    label: t('admin.rolename'),
    fontSize: '18px',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      colProps: {
        span: 24
      },
      componentProps: {
        props: {
          label: 'name',
          value: 'id'
        }
      },
      optionApi: async () => {
        const res = await getRoleApi()
        return res.data.items
      }
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          const roleid = data.row.roleid
          return (
            <ElTag type={roleid === 1 ? 'primary' : 'success'}>
              {roleid === 1 ? '管理员' : '组长'}
            </ElTag>
          )
        }
      }
    }
  },
  // {
  //   field: 'permission',
  //   label: t('admin.permission'),
  //   hidden: true,
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     component: 'TreeSelect',
  //     colProps: {
  //       span: 24
  //     },
  //     componentProps: {
  //       style: {
  //         width: '500px',
  //         height: '40px',
  //         fontSize: '18px'
  //       },
  //       renderAfterExpand: false,
  //       multiple: true,
  //       filterable: true,
  //       showCheckbox: true,
  //       checkStrictly: true,
  //       checkOnClickNode: true,
  //       // 设置下拉面板的最大高度
  //       maxHeight: '300px',
  //       // 设置下拉面板的样式
  //       popperStyle: {
  //         width: '00px',
  //         height: '400px',
  //         maxHeight: '400px',
  //         overflow: 'auto'
  //       },
  //       popperClass: 'custom-tree-select-popper',
  //       filterNodeMethod: (value, data) => data.label.includes(value),
  //       data: treeSelectData
  //     },
  //   },
  //   table: {
  //     align: 'center',
  //     headerAlign: 'center'
  //   }
  // },
  // {
  //   field: 'password',
  //   label: t('admin.password'),
  //   hidden: true,
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     component: 'Input',
  //     colProps: {
  //       span: 24
  //     },
  //     componentProps: {
  //       showPassword: true,
  //       style: {
  //         width: '500px',
  //         height: '40px',
  //         fontSize: '18px'
  //       },
  //     },
  //   }
  // },
  // {
  //   field: 'grps',
  //   label: t('admin.group'),
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     component: 'Select',
  //     colProps: {
  //       span: 24
  //     },
  //     componentProps: {
  //       style: {
  //         width: '500px',
  //         height: '40px',
  //         fontSize: '16px'
  //       },
  //       options: [
  //       {
  //         label: '分组1',
  //         value: '1'
  //       },
  //       {
  //         label: '分组2',
  //         value: '2'
  //       }
  //     ]
  //     }
  //   },
  //   table: {
  //     align: 'center',
  //     headerAlign: 'center',
  //     slots: {
  //       default: (data: any) => {
  //         if (!data.row.grps || !Array.isArray(data.row.grps)) {
  //           return <span>-</span>
  //         }
          
  //         return (
  //           <div>
  //             {data.row.grps.map((item: any, index: number) => (
  //               <ElTag key={index} type="success" style={{ margin: '2px' }}>
  //                 {item.name || item}
  //               </ElTag>
  //             ))}
  //           </div>
  //         )
  //       }
  //     }
  //   }
  // },
  {
    field: 'status',
    label: t('admin.status'),
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      // hidden: true,
      componentProps: {
        options: [
          {
            label: '启用',
            value: 0
          },
          {
            label: '禁用',
            value: 1
          }
        ]
      }
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          const status = data.row.status
          return (
            <ElTag type={status === 1 ? 'danger' : 'success'}>
              {status === 1 ? '禁用' : '启用'}
            </ElTag>
          )
        }
      }
    }
  },
  {
    field: 'ctime',
    label: t('admin.ctime'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'remarks',
    label: t('admin.remarks'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      },
      componentProps: {
        type: 'textarea',
        rows: 2
      }
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  // {
  //   field: 'action',
  //   width: '260px',
  //   label: t('tableDemo.action'),
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     hidden: true
  //   },
  //   detail: {
  //     hidden: true
  //   },
  //   table: {
  //     slots: {
  //       default: (data: any) => {
  //         return (
  //           <>
  //             <BaseButton type="primary" onClick={() => action(data.row, 'edit')}>
  //               {t('exampleDemo.edit')}
  //             </BaseButton>
  //             <BaseButton type="success" onClick={() => action(data.row, 'detail')}>
  //               {t('exampleDemo.detail')}
  //             </BaseButton>
  //             <BaseButton type="danger" onClick={() => delData(data.row)}>
  //               {t('exampleDemo.del')}
  //             </BaseButton>
  //           </>
  //         )
  //       }
  //     }
  //   }
  // }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TableData | null>(null)
const actionType = ref('')

const AddAction = async () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = null
  actionType.value = ''
  
  // 获取用户选项数据
  // await getUserOptions()
  
  dialogVisible.value = true
}

const delLoading = ref(false)

const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = async (row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveTableApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <!-- <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('exampleDemo.del') }}
      </BaseButton> -->
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total,
        layout: '->, total, sizes, prev, pager, next, jumper'
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :maxHeight="400">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <!-- <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template> -->
    <template #footer>
      <div v-if="actionType === 'edit'" style="display: flex; justify-content: space-between; align-items: center;">
        <!-- <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
          {{ t('exampleDemo.del') }}
        </BaseButton> -->
        <div>
          <BaseButton
            type="primary"
            :loading="saveLoading"
            @click="save"
            style="margin-right: 8px;"
          >
            {{ t('exampleDemo.save') }}
          </BaseButton>
          <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
        </div>
      </div>
      <div v-else>
        <BaseButton
          type="primary"
          :loading="saveLoading"
          @click="save"
          style="margin-right: 8px;"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </div>
    </template>
  </Dialog>
</template>
<!-- <style scoped>
:deep(.el-form-item__label) {
  font-size: 16px !important;
  padding-top: 10px !important;
}
</style> -->